<template>
  <v-dialog
    v-model="dialogFormVisible"
    max-width="800px"
    persistent
  >
    <v-card class="rounded-xl">
      <v-card-title class="d-flex align-center">
        <span>{{ title }}</span>
        <v-spacer></v-spacer>
        <v-btn
          icon="mdi-close"
          variant="text"
          @click="close"
        ></v-btn>
      </v-card-title>

      <v-card-text>
        <v-form ref="formRef" v-model="formValid">
          <v-row>
            <v-col cols="12" md="6">
              <v-text-field
                v-model="form.optionCode"
                label="参数编号"
                :rules="rules.optionCode"
                :disabled="!formStatus"
                variant="outlined"
                density="compact"
                required
              ></v-text-field>
            </v-col>

            <v-col cols="12" md="6">
              <v-text-field
                v-model="form.optionName"
                label="参数名称"
                :rules="rules.optionName"
                variant="outlined"
                density="compact"
                required
              ></v-text-field>
            </v-col>

            <v-col cols="12" md="6">
              <v-text-field
                v-model="form.optionValue"
                label="参数值"
                variant="outlined"
                density="compact"
              ></v-text-field>
            </v-col>

            <v-col cols="12" md="6">
              <v-textarea
                v-model="form.remark"
                label="备注"
                variant="outlined"
                density="compact"
                rows="3"
                auto-grow
              ></v-textarea>
            </v-col>
          </v-row>
        </v-form>
      </v-card-text>

      <v-card-actions class="px-6 pb-4">
        <v-spacer></v-spacer>
        <v-btn
          variant="outlined"
          @click="close"
        >
          取消
        </v-btn>
        <v-btn
          color="primary"
          :loading="saveLoading"
          @click="save"
        >
          确定
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue';
import { doInsert, doUpdate } from '@/api/system/options/SysOptionsManagement';
import { formateDate } from '@/utils/format';
import { isNull } from '@/utils/validate';
import { validatorRule } from '@/utils/validateRule';
import { useMessage } from '@/composables/useMessage';

const { proxy } = getCurrentInstance();
const { success: showSuccess, error: showError } = useMessage();

// 响应式数据
const dialogFormVisible = ref(false);
const formValid = ref(false);
const formStatus = ref(true);
const saveLoading = ref(false);
const title = ref('');

// 表单数据
const form = reactive({
  version: 0
});

// 表单引用
const formRef = ref();

// 验证规则
const rules = {
  optionCode: [
    v => !!v || '参数编号不能为空',
    v => validatorRule.IS_GENERAL.validator(null, v, () => {}) || '参数编号格式不正确'
  ],
  optionName: [
    v => !!v || '参数名称不能为空',
    v => validatorRule.IS_GENERAL_WITH_CHINESE.validator(null, v, () => {}) || '参数名称格式不正确'
  ]
};

// 暴露方法
defineExpose({
  showEdit
});

// 事件定义
const emit = defineEmits(['fetchData']);

/**
 * 显示编辑对话框
 */
function showEdit(row) {
  if (!row) {
    title.value = '添加参数';
    formStatus.value = true;
    // 重置表单
    Object.keys(form).forEach(key => {
      if (key === 'version') {
        form[key] = 0;
      } else {
        delete form[key];
      }
    });
  } else {
    title.value = '编辑参数';
    formStatus.value = false;
    // 复制数据
    Object.assign(form, row);
  }
  dialogFormVisible.value = true;
}

/**
 * 关闭对话框
 */
function close() {
  dialogFormVisible.value = false;
  formStatus.value = true;
  saveLoading.value = false;
  
  // 重置表单
  if (formRef.value) {
    formRef.value.reset();
  }
  
  // 重置数据
  Object.keys(form).forEach(key => {
    if (key === 'version') {
      form[key] = 0;
    } else {
      delete form[key];
    }
  });
}

/**
 * 保存数据
 */
async function save() {
  if (!formRef.value) return;
  
  const { valid } = await formRef.value.validate();
  if (!valid) {
    showError('请检查表单输入');
    return;
  }

  saveLoading.value = true;
  
  try {
    // 处理表单数据
    handlerFormData(form);

    let response;
    if (!isNull(form.id)) {
      // 更新
      response = await doUpdate(form);
    } else {
      // 新增
      response = await doInsert(form);
    }

    showSuccess(response.msg || '操作成功');
    emit('fetchData');
    close();
  } catch (error) {
    console.error('保存失败:', error);
    showError('保存失败');
  } finally {
    saveLoading.value = false;
  }
}

/**
 * 处理表单数据
 */
function handlerFormData(formData) {
  if (!isNull(formData)) {
    for (let key in formData) {
      // 对于时间类进行处理
      if ("[object Date]" === Object.prototype.toString.call(formData[key])) {
        formData[key] = formateDate(formData[key], 'yyyy-MM-dd hh:mm:ss');
      }
    }
  }
}
</script>

<style scoped>
.v-card-title {
  font-weight: 600;
}
</style>
